/*
 * SimGui.java
 *
 * Created on May 24, 2008, 10:42 AM
 */

package p2p.simulator.gui;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.Timer;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import p2p.simulator.Simulator;
import p2p.simulator.network.NetworkFilter;

/**
 *
 * @author  papalukg
 */
public class SimGui extends javax.swing.JFrame implements Runnable {
    private Simulator S;
    private String protocolPackage;
    private int phase;
    private int delay;
   
    private javax.swing.Timer tm;
    
    ActionListener actionPerformer = new java.awt.event.ActionListener() {

        public void actionPerformed(ActionEvent e) {
            //statusBar1.updateStatusLabel("Ready");
            statusBar1.setReady(true);
        }
    };
        
    /** Creates new form SimGui */
    public SimGui(Simulator S) {
           
        delay = 2000;
        tm = new Timer(delay, actionPerformer);   
        this.S = S;
        protocolsJMenuItems = new Vector<JMenuItem>();
        isProtocolSelected = false;
        
        initComponents();
        listProtocols();
        
        paintTabs();
        
        statusBar1.setReady(true);
        statusBar1.updateStatusLabel("Ready");
        SimTabs.setEnabled(isProtocolSelected);
        setVisible(true);
    }
    
    public void run() {
        int n = 0, desiredNodes = 0, counter = 0;
        String str;
        
        while (true) {
            
            if (SimTabs != null)
                desiredNodes = SimTabs.getSetUpTab().getNumOfNodes();
            if (desiredNodes > 0)
                n = (int) S.getNofPeers();
            
            if (!statusBar1.isReady())
                tm.start();
        
            if (isProtocolSelected() && SimTabs.getSetUpTab().isShowing() && n <= desiredNodes) 
                SimTabs.getSetUpTab().updateProgressBar(n);
            
            if (SimTabs.getOperationsTab().isShowing())
                SimTabs.getOperationsTab().updateMsgArea(NetworkFilter.getLogMsg());
            
            // Disable tabs an enable menu
            if (!isProtocolSelected()) {
                SimTabs.setEnabled(false);
                for(int i = 0; i < protocolsJMenuItems.size(); i++)
                    protocolsJMenuItems.get(i).setEnabled(true);
            }
            
            try {
                Thread.sleep(50);  
                //this.repaint();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        statusBar1 = new p2p.simulator.gui.StatusBar();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu5 = new javax.swing.JMenu();
        jMenu6 = new javax.swing.JMenu();
        quitMenuItem = new javax.swing.JMenuItem();
        jMenu8 = new javax.swing.JMenu();
        helpMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("D-P2P-Sim");
        getContentPane().setLayout(new java.awt.BorderLayout(0, 1));
        getContentPane().add(statusBar1, java.awt.BorderLayout.PAGE_END);

        jMenu5.setText("File");
        jMenu5.setFont(new java.awt.Font("Dialog", 0, 12));

        jMenu6.setText("Protocol");
        jMenu6.setFont(new java.awt.Font("Dialog", 0, 12));
        jMenu5.add(jMenu6);

        quitMenuItem.setFont(new java.awt.Font("Dialog", 0, 12));
        quitMenuItem.setText("Quit");
        quitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitMenuItemActionPerformed(evt);
            }
        });
        jMenu5.add(quitMenuItem);

        jMenuBar2.add(jMenu5);

        jMenu8.setText("Help");
        jMenu8.setFont(new java.awt.Font("Dialog", 0, 12));

        helpMenuItem.setFont(new java.awt.Font("Dialog", 0, 12));
        helpMenuItem.setText("Help Contents");
        helpMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu8.add(helpMenuItem);

        aboutMenuItem.setFont(new java.awt.Font("Dialog", 0, 12));
        aboutMenuItem.setText("About");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu8.add(aboutMenuItem);

        jMenuBar2.add(jMenu8);

        setJMenuBar(jMenuBar2);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    protected void protocolSelected (boolean f) {
        isProtocolSelected = f;
    }
    
    protected boolean isProtocolSelected() {            
        return isProtocolSelected;
    }
    
    private void listProtocols() {
        
        JMenuItem protocolMenuItem;
        String protocol;
        int index;
        
        for (int i = 0; i < S.getProtocols().length; i++) {
            protocol = S.getProtocols()[i];
            index = protocol.lastIndexOf(".jar");
            protocol = protocol.substring(0, index);
            protocolMenuItem = new JMenuItem();
            protocolsJMenuItems.add(protocolMenuItem);
            protocolMenuItem.setFont(new java.awt.Font("Dialog", 0, 12));
            protocolMenuItem.setText(protocol);
            protocolMenuItem.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    protocolSelected(evt);
                }
            });
            jMenu6.add(protocolMenuItem);
        }
    }
    
    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        // TODO add your handling code here:
        JTextPane jTextPane1 = new JTextPane();
        jTextPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
        jTextPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jTextPane1.setEditable(false);
        jTextPane1.setPreferredSize(new java.awt.Dimension(350, 60));
        String[] initString =
        { "D-P2P-Sim v1.0 is a distributed simulator for P2P overlay networks."+
          "For more details visit our site: ",
          "http://www.students.ceid.upatras.gr/~papalukg",
          "."
        };
        
        String[] initStyles = { "regular", "mail", "regular"};
        
        //JTextPane textPane = new JTextPane();
        StyledDocument doc = jTextPane1.getStyledDocument();
        addStylesToDocument(doc);
        
        try {
            for (int i=0; i < initString.length; i++) {
                doc.insertString(doc.getLength(), initString[i],
                        doc.getStyle(initStyles[i]));
            }
        } catch (BadLocationException ble) {
            System.err.println("Couldn't insert initial text into text pane.");
        }
        
        JOptionPane.showMessageDialog(this, jTextPane1, "About Nbdt*", JOptionPane.PLAIN_MESSAGE);
        
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        help = new HelpContents();
        getContentPane().remove(activePanel);
        getContentPane().add(help, java.awt.BorderLayout.CENTER);
        pack();
        activePanel = help;
    }//GEN-LAST:event_jMenuItem1ActionPerformed

private void quitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitMenuItemActionPerformed
// TODO add your handling code here:
    S.exitSimulation();
    System.exit(0);
}//GEN-LAST:event_quitMenuItemActionPerformed

    private void protocolSelected(java.awt.event.ActionEvent evt) {
        
        JMenuItem protocol;
                    
        if (!isProtocolSelected) {
            protocolSelected(true);
            SimTabs.setEnabled(true);
            protocol = (JMenuItem)evt.getSource();
            S.setProtocolPkg(protocol.getText()+".jar");
            
            for(int i = 0; i < protocolsJMenuItems.size(); i++)
                if (!protocol.equals(protocolsJMenuItems.get(i)))
                    protocolsJMenuItems.get(i).setEnabled(false);
//            System.out.println(protocol.getText()+".jar");
        }
        //S.setProtocolPkg(protocolPackage);
        activePanel.setVisible(false);
        SimTabs.setVisible(true);
        getContentPane().remove(activePanel);
        getContentPane().add(SimTabs, java.awt.BorderLayout.CENTER);
        pack();
        activePanel = SimTabs;
    }
    
    private void paintTabs() {
        
        SimTabs = new SimTabs(S, statusBar1, this);
        getContentPane().add(SimTabs, java.awt.BorderLayout.CENTER);
        pack();
        activePanel = SimTabs;
    }
        
    protected void addStylesToDocument(StyledDocument doc) {
        //Initialize some styles.
        Style def = StyleContext.getDefaultStyleContext().
                        getStyle(StyleContext.DEFAULT_STYLE);

        Style regular = doc.addStyle("regular", def);
        StyleConstants.setFontFamily(def, "Dialog");
        StyleConstants.setFontSize(regular, 12);
        StyleConstants.setForeground(def, new Color(51,51,51));
        
        StyleConstants.setAlignment(regular, StyleConstants.ALIGN_JUSTIFIED);
        doc.setParagraphAttributes(0, doc.getLength(), regular, false);
        
        Style s = doc.addStyle("italic", regular);
        StyleConstants.setItalic(s, true);

        s = doc.addStyle("bold", regular);
        StyleConstants.setBold(s, true);

        s = doc.addStyle("small", regular);
        StyleConstants.setFontSize(s, 10);

        s = doc.addStyle("large", regular);
        StyleConstants.setFontSize(s, 16);
        
        s = doc.addStyle("mail", regular);
        StyleConstants.setForeground(s, Color.BLUE);
        
        /*s = doc.addStyle("icon", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        ImageIcon pigIcon = createImageIcon("images/Pig.gif", "a cute pig");
      
        if (pigIcon != null) {
            StyleConstants.setIcon(s, pigIcon);
        }

        s = doc.addStyle("button", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
        ImageIcon soundIcon = createImageIcon("images/sound.gif",
                                              "sound icon");
        JButton button = new JButton();
        if (soundIcon != null) {
            button.setIcon(soundIcon);
        } else {
            button.setText("BEEP");
        }
        button.setCursor(Cursor.getDefaultCursor());
        button.setMargin(new Insets(0,0,0,0));
        button.setActionCommand(buttonString);
        button.addActionListener(this);
        StyleConstants.setComponent(s, button);
         */
    }
    /**
     * @param args the command line arguments
     */
    /*public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (Exception e) {
                }
                new SimGui().setVisible(true);
            }
        });
    }*/
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem helpMenuItem;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenu jMenu8;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem quitMenuItem;
    private p2p.simulator.gui.StatusBar statusBar1;
    // End of variables declaration//GEN-END:variables
    private SimTabs SimTabs;
    private HelpContents help;
    private Container activePanel;
    private Vector<JMenuItem> protocolsJMenuItems;
    private boolean isProtocolSelected;
}
